/*
    Copyright 2009 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package ot;

import java.util.*;
import java.io.*;

/** A cache of objects. Objects are accessible by {@link LocO}.
 *
 * @author Barnet Wagman
 */
public class OtableCache {

    List<Serializable> objs;
    List<String> keys;
    HashMap<String,Serializable> ht;

    int cacheSize;
    int decrement;

    public OtableCache(int cacheSize, int decrement) {
        this.cacheSize = cacheSize;
        this.decrement = decrement;
        objs = new ArrayList<Serializable>();
        keys = new ArrayList<String>();
        ht = new HashMap<String,Serializable>();
    }

    public synchronized Serializable get(LocO loc) {
        return( ht.get(loc.toString()) );
    }

    public synchronized void add(LocO loc,Serializable obj) {
        if ( objs.size() >= cacheSize ) shrink();
        objs.add(obj);
        String key = loc.toString();
        keys.add(key);
        ht.put(key,obj);
    }

    private void shrink() {

        for ( int i = 0; i < decrement; i++ ) {
            String key = keys.get(0);
            keys.remove(0);
            objs.remove(0);
            ht.remove(key);
        }
        
    }
}
